import React, { useState, useEffect } from 'react'

import { DatePicker, message } from 'antd';

import moment from 'moment';

import YearSelect from '@/pages/SalaryManage/components/YearSelect';
import DutySelect from '@/pages/SalaryManage/components/DutySelect';
import useSalaryItemsSetting from './useSalaryItemsSetting';
import useDepartmentSetting from './useDepartmentSetting';
import useOrganizationTree from './useOrganizationTree';

import { screenSettingMap } from '../paramMap';
import SettingItems from '../component/SettingItems';
import SalaryItemsSelect from '../component/SalaryItemsSelect';


import styles from '../style.less'

const { RangePicker } = DatePicker;
const rangePickerMode = ['month', 'month']

const offsetDays = 86400000 * 30

const format = 'YYYY-MM'

// 日期范围套件
const RangePickerWrapper = ({ endMonth, endYear, startMonth, startYear, changeValuesHandle }) => {
    const [rangePickerValue, setRangePickerValue] = useState([])
    const [selectPriceDate, setSelectPriceDate] = useState('')

    useEffect(() => {
       setRangePickerValue([moment(`${startYear}-${startMonth < 10 ? '0' : ''}${startMonth}`), moment(`${endYear}-${endMonth < 10 ? '0' : ''}${endMonth}`)])
    }, [endMonth, endYear, startMonth, startYear])

    const disabledDate = current => {
        if (selectPriceDate) {
            const selectV = moment(selectPriceDate, format).valueOf()
            return current > moment(new Date(selectV + offsetDays), format) ||
                current < moment(new Date(selectV - offsetDays), format)
        }
            return false
    }

    const handlePanelChange = (value, mode) => {
        if (mode[0] === 'date') {
            setSelectPriceDate(value[0])
        } else {
            setSelectPriceDate(value[1])
        }
        setRangePickerValue(value)
    };

    const openChange = status => {
        const newEndMonth = rangePickerValue[1].month() + 1
        const newEndYear = rangePickerValue[1].year()
        const newStartMonth = rangePickerValue[0].month() + 1
        const newStartYear = rangePickerValue[0].year()

        if (newEndMonth === endMonth &&
            newEndYear === endYear &&
            newStartMonth === startMonth &&
            newStartYear === startYear) {
            return
        }

        if (!status) {
            if (newEndYear - newStartYear > 2 ||
                (newEndMonth + 12 * (newEndYear - newStartYear) - newStartMonth) >= 12) {
                message.error('起止年月不能超过12个月')
                return
            }
            changeValuesHandle({
                endMonth: newEndMonth,
                endYear: newEndYear,
                startMonth: newStartMonth,
                startYear: newStartYear
            })
        }
    }

    return (
        <RangePicker
            placeholder={['开始年月', '结束年月']}
            format={format}
            value={rangePickerValue}
            mode={rangePickerMode}
            allowClear={false}
            onOpenChange={openChange}
            onPanelChange={handlePanelChange}
            disabledDate={disabledDate}
            style={{ width: 210 }}
        />
    )
}

// 年份套件
const YearSelectWrapper = ({ year, organizationCode, changeValuesHandle }) => {
    const onChangeYear = value => {
        if (value !== year) {
            changeValuesHandle({
                year: value
            })
        }
    }

    return <YearSelect
        className={styles.ml15}
        value={year}
        onChange={onChangeYear}
        organizationCode={organizationCode}
        styles={{ marginRight: 0 }}
        size="default" />
}

// 薪资项单选
const SalarySelectWrapper = ({ salaryItemIdList, organizationCode, changeValuesHandle }) => {
    const onChange = value => {
        changeValuesHandle({
            salaryItemIdList: [value]
        })
    }

    const itemValue = salaryItemIdList && salaryItemIdList.length > 0 ? salaryItemIdList[0] : undefined

    return (
        <SalaryItemsSelect
            className={styles.ml15}
            organizationCode={organizationCode}
            itemType={9}
            extraType={0}
            value={itemValue}
            onChange={onChange}
            style={{ width: 210 }}
        />
    )
}

// 薪资项多选
const SalaryTreeWrapper = ({ salaryItemIdList, organizationCode, changeValuesHandle }) => {
    const onChange = value => {
        if (value.length > 10) {
            message.error('最多只能选10个')
            return
        }
         changeValuesHandle({
            salaryItemIdList: value
        })
    }

    return (
        <SalaryItemsSelect
            className={styles.ml15}
            organizationCode={organizationCode}
            itemType={9}
            extraType={0}
            value={salaryItemIdList}
            onChange={onChange}
            mode="multiple"
            maxTagCount={1}
            maxTagTextLength={8}
            style={{ width: 210 }}
            treeCheckable
            multiple
        />
    )
}

// 岗位多选
const DutyWrapper = ({ dutyCodeList, changeValuesHandle }) => {
    const [state, setState] = useState(dutyCodeList || [])
    useEffect(() => {
        setState(dutyCodeList)
    }, [dutyCodeList])
    const onChange = value => {
        if (value.length > 10) {
            message.error('最多只能选10个')
            return
        }
        setState(value)
    }

    const onBlur = (...arg) => {
        changeValuesHandle({
            dutyCodeList: arg[0]
        })
    }

    return (
        <DutySelect
            className={styles.ml15}
            style={{ width: 210 }}
            maxTagCount={1}
            maxTagTextLength={8}
            value={state}
            onBlur={onBlur}
            onChange={onChange}
            allowClear={false}
            mode="multiple"
            showSearch />
    )
}

// 薪资项参考值设置
const SalaryItemsWrapper = ({ salaryItemInfoList, organizationCode, changeValuesHandle }) => {
    const onChange = value => {
        changeValuesHandle({
            salaryItemInfoList: value
        })
    }

    const {
        render: renderSalaryItems,
        onShowSalaryItemsSetting
    } = useSalaryItemsSetting(salaryItemInfoList, organizationCode, onChange);

    return (
        <>
            <SettingItems title="薪资项参考值" onClick={onShowSalaryItemsSetting} />
            {renderSalaryItems()}
        </>
    )
}

// 组织机构参考值设置
const DepartmentWrapper = ({ departmentInfoList, organizationCode, changeValuesHandle }) => {
    const onChange = value => {
        changeValuesHandle({
            departmentInfoList: value
        })
    }

    const {
        render: renderDepartment,
        onShowDepartmentSetting
    } = useDepartmentSetting(departmentInfoList, organizationCode, onChange);

    return (
        <>
            <SettingItems title="组织机构参考值" onClick={onShowDepartmentSetting} />
            {renderDepartment()}
        </>
    )
}

// 组织机构多选套件
const DepartmentTreeWrapper = ({ departmentCodeList, organizationCode, isContainSubOrg, changeValuesHandle }) => {
    const onChange = (arr, isContain) => {
        changeValuesHandle({
            departmentCodeList: arr,
            isContainSubOrg: isContain ? 1 : 0
        })
    }

    const {
        render: renderDepartmentTree
    } = useOrganizationTree(departmentCodeList, organizationCode, isContainSubOrg, onChange);

    return (
        <>
            {renderDepartmentTree()}
        </>
    )
}

const useMyChartSetting = ({
    endMonth,
    endYear,
    globalType,
    salaryItemIdList,
    salaryItemInfoList,
    departmentInfoList,
    departmentCodeList,
    dutyCodeList,
    isContainSubOrg,
    startMonth,
    startYear,
    year
 }, organizationCode, changeConfig) => {
    const changeValues = val => {
        changeConfig(val)
    }
    return {
        render() {
            return <>
                {/* 日期区间 */}
                {
                    screenSettingMap.rangePicker.includes(globalType) ? (
                        <RangePickerWrapper
                            endMonth={endMonth}
                            endYear={endYear}
                            startMonth={startMonth}
                            startYear={startYear}
                            changeValuesHandle={changeValues}
                        />
                    ) : null
                }
                {/* 年份单选 */}
                {
                    screenSettingMap.yearSelect.includes(globalType) ? (
                        <YearSelectWrapper
                            year={year}
                            organizationCode={organizationCode}
                            changeValuesHandle={changeValues}
                        />
                    ) : null
                }
                {/* 薪资项单选 */}
                {
                    screenSettingMap.salaryItemSelect.includes(globalType) ? (
                        <SalarySelectWrapper
                            salaryItemIdList={salaryItemIdList}
                            organizationCode={organizationCode}
                            changeValuesHandle={changeValues}
                        />
                    ) : null
                }
                {/* 薪资项多选 */}
                {
                    screenSettingMap.salaryItemTree.includes(globalType) ? (
                        <SalaryTreeWrapper
                            salaryItemIdList={salaryItemIdList}
                            organizationCode={organizationCode}
                            changeValuesHandle={changeValues}
                        />
                    ) : null
                }
                {/* 岗位多选 */}
                {
                    screenSettingMap.dutyTree.includes(globalType) ? (
                        <DutyWrapper
                            dutyCodeList={dutyCodeList}
                            changeValuesHandle={changeValues}
                        />
                    ) : null
                }
                {/* 组织机构多选 */}
                {
                    screenSettingMap.orgTree.includes(globalType) ? (
                        <DepartmentTreeWrapper
                            departmentCodeList={departmentCodeList}
                            organizationCode={organizationCode}
                            isContainSubOrg={isContainSubOrg}
                            changeValuesHandle={changeValues} />
                    ) : null
                }
                {/* 薪资项参考值 */}
                {
                    screenSettingMap.salaryItemSetting.includes(globalType) ? (
                        <SalaryItemsWrapper
                            salaryItemInfoList={salaryItemInfoList}
                            organizationCode={organizationCode}
                            changeValuesHandle={changeValues}
                        />
                    ) : null
                }
                {/* 组织机构参考值 */}
                {
                    screenSettingMap.orgSetting.includes(globalType) ? (
                        <DepartmentWrapper
                            departmentInfoList={departmentInfoList}
                            organizationCode={organizationCode}
                            changeValuesHandle={changeValues}
                    />
                    ) : null
                }
            </>
        }
    }
};

export default useMyChartSetting;
